package test;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.io.entity.EntityUtils;

/**
 * 连接池管理器
 * 减少连接开销
 */
public class HttpClientPoolTest1 {
    public static void main(String[] args) throws Exception {
        //创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //使用连接池管理器发起请求
        doGet(cm);
        doGet(cm);
    }
    private static void doGet(PoolingHttpClientConnectionManager cm) throws Exception {
        //不是每次创建新的HttpClient，而是从连接池当中获取HttpClient
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        HttpGet httpGet = new HttpGet("https://www.runoob.com/");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if( response.getCode() == 200){
            String content = EntityUtils.toString(response.getEntity(), "utf8");
            System.out.println(content.length());
        }
        //不能关闭httpClient，这是是由连接池管理
        //httpClient.close();
        response.close();
    }
}